package com.hkx.smipleemps.servlet;

import com.hkx.smipleemps.common.domain.Admin;
import com.hkx.smipleemps.common.utils.HibernateUtils;
import com.hkx.smipleemps.service.AdminService;
import com.hkx.smipleemps.service.AdminServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/submitChangePassword.do")
public class SubmitChangePasswordServlet extends HttpServlet {
    AdminService adminService = new AdminServiceImpl();
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String idStr = request.getParameter("id");// "1"  ----> 1
        Integer id = Integer.parseInt(idStr);//把字符串形式的数字转成整型！
        String oldPassword = request.getParameter("old_password");
        String newPassword = request.getParameter("new_password");
        Admin admin = adminService.getAdminById(id);
        if(admin.getPassword().equals(oldPassword)){
            admin.setPassword(newPassword);
//            HibernateUtils.beginSessionTransaction(); 提取到过滤器中
            adminService.updateAdmin(admin);
//            HibernateUtils.commitAndCloseSession();
            request.setAttribute("msg","修改密码成功，请重新登录");
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }else{
            request.setAttribute("msg","旧密码错误");
            request.setAttribute("admin",admin);
            request.getRequestDispatcher("/changePassword.jsp").forward(request,response);
        }
    }
}
